from typing import List,Union
import sys,os
#sys.path.append("C:\\Users\\Administrator\\Desktop\\VSCode\\IMS")
    
from fastapi import APIRouter,Depends,UploadFile,File
from fastapi.responses import FileResponse
# from fastapi.logger import logger
from tortoise.transactions import atomic,in_transaction
from tortoise.expressions import Q

from models import Project,User,ProjectMembers,ProjectFiles,ProjectGroups
from scheams import (Project_Pydantic,ProjectIn_Pydantic
                     ,Response200,Response400
                     ,ProjectMembers_Pydantic,ProjectInWithId_Pydantic
                     ,ProjectMembersWithId_Pydantic
                     ,ProjectFiles_Pydantic,ProjectGroups_Pydantic
                     ,User_Pydantic)
from core import deps,config,get_logger
from utils import project_utils

logger = get_logger(__name__)

project_group = APIRouter(tags=["项目评审组相关"],dependencies=[Depends(deps.get_current_user)])


# @project_group.get("/getProjectGroups",summary="获取评审组枚举")
# async def getProjectGroups():
#     return Response200(data=[ config.settings.ProjectGroupName(v).value for k,v in config.settings.ProjectGroupName.__members__.items()])

@project_group.get("/getGroupMembers/{group_name}",summary="获取评审组成员")
async def getGroupMembers(group_name: config.settings.ProjectGroupName):
    
    logger.debug("---------{}".format(User.filter(Q(username__in=[ k["group_member_id"] for k in await ProjectGroups.filter(group_name=group_name).values("group_member_id")])).sql()))
    
    logger.debug("------{}".format(
        await ProjectGroups.filter(group_name=group_name).values_list("id","group_name","group_member__username","group_member__department","group_member_role")
    ))
    
    # return Response200(data=await User_Pydantic.from_queryset(User.filter(Q(username__in=[ k["group_member_id"] for k in await ProjectGroups.filter(group_name=group_name).values("group_member_id")]))))
    return Response200(data=await ProjectGroups.filter(group_name=group_name).values("id","group_name","group_member_role",username="group_member__username",department="group_member__department"))


@project_group.post("/addProjectGroupMembers",summary="增加成员")
async def addProjectGroupMembers(group_name: config.settings.ProjectGroupName,username: str,role: config.settings.ProjectGroupMemberRole):
    
    ## 检测该成员是否已在该评审组中
    member: ProjectGroups = await ProjectGroups.filter(group_name=group_name,group_member_id=username)
    logger.debug("------------------{}".format(member))
    member = member[0] if len(member) > 0 else None
    
    if member and member.group_member_role != role:
        # 存在该成员但角色不同 修改角色
        logger.debug("存在该成员但角色不同 修改角色")
        
        # 若该成员为组长 则不可变更为组员，返回报错
        if member.group_member_role == config.settings.ProjectGroupMemberRole.LEADER:
            return Response400(msg="该成员是组长，不可变更为组员；若要变更为组员，需先指定另一组长")
        else:
            # 若为组员变更为组长 则先将原组长变更为组员，再将此组员变组长
            async with in_transaction():
                # 原组长 -> 组员
                logger.debug("============{}".format(ProjectGroups.select_for_update().filter(group_name=group_name,group_member_role=role).update(group_member_role=config.settings.ProjectGroupMemberRole.NORMAL)))
                logger.debug("============{}".format(ProjectGroups.filter(group_name=group_name,group_member_role=role).update(group_member_role=config.settings.ProjectGroupMemberRole.NORMAL)))
                await ProjectGroups.select_for_update().filter(group_name=group_name,group_member_role=role).update(group_member_role=config.settings.ProjectGroupMemberRole.NORMAL)
                # await ProjectGroups.filter(group_name=group_name,group_member_role=role).update(group_member_role=config.settings.ProjectGroupMemberRole.NORMAL)
                # 该组员 -> 组长
                member.group_member_role = role
                await member.save()
                return Response200(msg="变更成功",data=await ProjectGroups_Pydantic.from_tortoise_orm(member))
    
    elif member and member.group_member_role == role:
        # 成员已存在该组中 且 角色相同 报错返回
        logger.debug("成员已存在该组中 且 角色相同")
        return Response400(msg="用户已存在该组中")
    else:
        # 成员不存在 
        logger.debug("成员不存在")
        
        # 该成员角色为组长，则判断该组是否存在组长，存在则报错返回，不存在则添加
        if role == config.settings.ProjectGroupMemberRole.LEADER.value and await ProjectGroups.filter(group_name=group_name,group_member_role=role):
            return Response400(msg="该组已存在组长")
        
        # 该成员角色为组员 直接添加
        return Response200(
            msg="增加成功"
            ,data=await ProjectGroups_Pydantic.from_tortoise_orm(
                await ProjectGroups.create(
                    group_name=group_name
                    ,group_member_id=username
                    ,group_member_role=role)
                )
            )

@project_group.delete("/delete_group_member",summary="删除评审组成员")
async def deleteProjectGroupMember(group_name: config.settings.ProjectGroupMemberRole,username: str):
    # 判断是否为组长 是则不可删除 否则删除
    member = await ProjectGroups.filter(group_name=group_name,group_member_id=username).first()
    if member and member.group_member_role == config.settings.ProjectGroupMemberRole.LEADER.value:
        return Response400(msg="该成员为组长，不可直接删除，删除该成员前请先指定另一组长")
    
    await member.delete()
    return Response200(msg="删除成功")